<template>
	<teleport to="#app">
		<view  >
			<view class="voice-recording-mask"  @touchmove.stop.prevent >
				<view class="voice-recording" >
					<view class="recording-circle" :class="{ 'recording-circle-cancel': recordCancel }"></view>
					<text class="recording-text">{{ recordingTip }}</text>
					<text class="timer">{{ formatTimer(timer) }}</text>
					<text class="record-cancel" :style="{ color: recordCancel ? '#ff4d4f' : '#fff' }">向上滑动取消</text>
				</view>
			</view>
	
	</view>	
		
	</teleport>

</template>

<script>
import checkPermissions from '@/utils/checkPermissions';
import { Images, Video } from '../utils/media.js';
import MessageSender from '../utils/MessageSender.js';

export default {
	name: 'recordManger',
	props: {
		toTarget: {
			type: Object,
			default: () => ({})
		},
		recordShow:{
			type:Boolean,
			default:false
		}
	},
	data() {
		return {
			isRecording: false,
			recordingTip: '正在录音...',
			recordStartTime: 0,
			recordCancel: false, // 标记是否取消录音
			recorderManager: null,
			systemInfo: {},
			startX: 0,
			startY: 0,
			timer:60,
			duration: 0 // 录音时长
		};
	},
	computed:{
		storeData(){
			return this.$store.state.msg
		}
	},

	mounted() {
		const hasPermission = checkPermissions('record', '麦克风');
		if (!hasPermission) {
			uni.showToast({ title: '需要麦克风权限才能录音', icon: 'none' });
			this.isRecording = false;
	    	return	
		} 

		this.recorderManager = uni.getRecorderManager();
		this.recorderManager.onStart(() => {
			this.setTimer();
			console.log('开始录音');
		});

		this.recorderManager.onStop(async (res) => {
			this.stoptimer();

			// 只有未取消且时长合格才上传
			if (!this.recordCancel) {
				try {
					const voiceInfo = await this.uploadVoice(res.tempFilePath);
					console.log('语音上传结果', voiceInfo);
					if (voiceInfo) {
						const messageSender = new MessageSender(this.storeData);
							console.log('语音消息', this.toTarget);
						const msg = await messageSender.sendVoice(this.toTarget, { ...voiceInfo, duration: this.duration });
					
						this.$emit('sendVoice', { duration: this.duration, ...voiceInfo });
					}
				} catch (e) {
					uni.showToast({ title: e.message || '发送失败', position: 'center', icon: 'none' });
				}
			}
		});

		this.recorderManager.onError((err) => {
			console.log('录音错误监听 ', err);
			this.stoptimer();
			this.duration = 0;
			this.isRecording = false;
		

			uni.showToast({ title: '录音失败，请重试', icon: 'none' });
		});
		
		// uni.$on('recordStart',res=>{
		// 	console.warn("录音状态",res);
			
		// 	if(res){
		// 		this.startRecord()
		// 	}else{
		// 		this.stopRecord()
		// 	}
		// })
	    uni.$on('recordCancel',res=>{
			this.recordCancel=res
			if(res){
					this.recordingTip = '松开取消发送';
			}else{
				this.recordingTip = '正在录音...';	
			}
       	
		})
		this.startRecord()
		
	},
	destroyed() {
		this.stopRecord()
		console.log('销毁录音组件');
		uni.$off('recordCancel')
		uni.$off('recordStart')
		this.stoptimer()
		this.recorderManager=null
		},
	methods: {
		setTimer() {
            console.log('11111111录音器');
			this.timer = 60; // 重置倒计时
			if(this.timerId){
				clearInterval(this.timerId)
				this.timerId=null
			}
			this.timerId = setInterval(() => {
				if (this.timer > 0) {
					console.log(this.timer);
					this.timer--;
					this.duration = 60 - this.timer;
				 console.log('NVUE 计时器：', this.timer);
					
				} else {
					this.stopRecord();
					uni.showToast({ title: '录音已达最大时长', icon: 'none' });
				}
			}, 1000);
		},

		// 停止定时器
		stoptimer() {
			if (this.timerId) {
				console.log('停止计时');
				clearInterval(this.timerId);
				this.timerId = null;
				this.timer = 60; // 重置
			}
		},

		// 格式化定时器显示
		formatTimer(second) {
		
			const min = Math.floor(second / 60);
			const sec = second % 60;
			
			return `${min.toString().padStart(2, '0')}:${sec.toString().padStart(2, '0')}`;
		},
		touchstart(e) {
		
			this.startY = e.touches[0].pageY;
		     console.log('...',e);	
			
			
		},
		// 开始录音
		startRecord(e) {
		
			uni.vibrateShort();
			this.isRecording = true;
			this.recordCancel = false;
			this.recordingTip = '正在录音...';
			this.recordStartTime = Date.now();

			const options = {
				duration: 60000,
				sampleRate: 44100,
				numberOfChannels: 1,
				encodeBitRate: 192000,
				format: 'mp3'
			};
			this.recorderManager.start(options);
		},

		// 结束录音
		stopRecord(e) {
		
			this.isRecording = false;
			this.recorderManager.stop();
			this.stoptimer();

			if (this.recordCancel) {
				uni.showToast({ title: '录音已取消', position: 'center', duration: 1000 });
				return;
			}
			const recordDuration = Date.now() - this.recordStartTime;
			if (recordDuration < 1500) {
				uni.showToast({ title: '录音时间太短', icon: 'none', duration: 1000 });
				return;
			}
		},

		// 处理录音滑动
		handleTouchMove(e) {
			console.log("移动.......",e);
			if (!this.isRecording) return;
			const currentY = e.touches[0].pageY;
			const moveY = currentY - this.startY;
			console.log("移动距离",moveY);
			if (moveY < -50) {
				// 向上滑动超过50rpx取消
				this.recordCancel = true;
				this.recordingTip = '松开取消发送';
			} else {
				this.recordCancel = false;
				this.recordingTip = '正在录音...';
			}
		},

		// 取消录音
		cancelRecord() {
			this.isRecording = false;
			this.recordCancel = true;
			if (this.recorderManager) {
				this.recorderManager.stop();
			}
			this.stoptimer();
		},

		// 上传语音
		async uploadVoice(path) {
			try {
				const uniqueId = Date.now();
				const uploadRes = await uniCloud.uploadFile({
					cloudPath: `voice/${uniqueId}.mp3`,
					filePath: path
				});
				if (!uploadRes.fileID) {
					throw new Error('语音上传失败');
				}
				const urlRes = await uniCloud.getTempFileURL({ fileList: [uploadRes.fileID] });
				return {
					voicePath: urlRes.fileList[0].tempFileURL,
					fileId: urlRes.fileList[0].fileID,
					duration: this.duration
				};
			} catch (error) {
				console.error('语音上传失败', error);
				uni.showToast({ title: '语音上传失败', icon: 'none' });
				return null;
			}
		}
	}
};
</script>

<style lang="scss" >
.voice-recording {
	width: 240rpx;
	height: 280rpx;
	background-color: rgba(0, 0, 0, 0.7);
	border-radius: 24rpx;
	display: flex;
	flex-direction: column;
	align-items: center;
	justify-content: center;
}
.voice-recording-mask {
	position: fixed;
	left: 0;
	top: 0;
	bottom: 0;
	right: 0;
	background-color: rgba(0, 0, 0, 0.5);
	z-index: 99999;
	display: flex;
	align-items: center;
	justify-content: center;
}

.recording-circle {
	width: 100rpx;
	height: 100rpx;
	border-radius: 50%;
	background-color: #ff4d4f;
	margin-bottom: 24rpx;
	animation: pulse 1.5s infinite;
}

.recording-circle-cancel {
	background-color: #666;
	animation: none;
}
.slot-container {
}

/* #ifndef APP-PLUS-NVUE */
@keyframes pulse {
	0% {
		transform: scale(1);
		opacity: 1;
	}
	50% {
		transform: scale(1.05);
		opacity: 0.8;
	}
	100% {
		transform: scale(1);
		opacity: 1;
	}
}
/* #endif */

.recording-text {
	color: #fff;
	font-size: 32rpx;
	margin-bottom: 8rpx;
}

.timer {
	color: #fff;
	font-weight: 600;
	font-size: 36rpx;
	margin-bottom: 16rpx;
}

.record-cancel {
	font-size: 24rpx;
	color: #fff;
}

/* 图标旋转样式 */
/* #ifndef APP-PLUS-NVUE */
.rotate-icon {
	transform: rotate(45deg);
	transition: transform 0.3s ease;
}
.default-icon {
	transition: transform 0.3s ease;
}
/* #endif */


</style>
